package com.qqtech.qquan.activity.service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.activity.dao.ActivitySignDao;
import com.qqtech.qquan.activity.enums.ActivityBaseCostTypeDictEnum;
import com.qqtech.qquan.activity.enums.ActivityBaseStatusDictEnum;
import com.qqtech.qquan.activity.enums.ActivityBaseTypeDictEnum;
import com.qqtech.qquan.activity.enums.ActivitySignStatusDictEnum;
import com.qqtech.qquan.activity.model.ActivityBaseVo;
import com.qqtech.qquan.activity.model.ActivitySign;
import com.qqtech.qquan.activity.model.ActivitySignQuery;
import com.qqtech.qquan.activity.model.ActivitySignVo;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.community.service.CommunityJoinService;
import com.qqtech.qquan.hi.service.HiCircleService;
import com.qqtech.qquan.order.enums.OrderBaseDeliveryStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseOrderTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBasePayTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseReturnStatusDictEnum;
import com.qqtech.qquan.order.enums.OrderBaseSubsidyTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderDeliverySendDeliveryTypeDictEnum;
import com.qqtech.qquan.order.enums.OrderDeliveryTypeDictEnum;
import com.qqtech.qquan.order.model.OrderBase;
import com.qqtech.qquan.order.model.OrderDelivery;
import com.qqtech.qquan.order.model.OrderItem;
import com.qqtech.qquan.order.service.OrderHandleService;
import com.qqtech.qquan.push.service.PushBizzService;
import com.qqtech.qquan.user.enums.UserIdentityTypeDictEnum;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.model.UserIdentityQuery;
import com.qqtech.qquan.user.model.UserIdentityVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserIdentityService;

@Service
public class ActivitySignServiceImpl extends BaseServiceImpl<ActivitySign>implements ActivitySignService {
	public static final Logger log = LoggerFactory.getLogger(ActivitySignServiceImpl.class);

	@Resource
	private ActivitySignDao activitySignDao;

	@Resource
	private UserBaseService userBaseService;

	@Resource
	private CommunityJoinService communityJoinService;

	@Resource
	private CircleMemberService circleMemberService;

	@Resource
	private UserIdentityService userIdentityService;

	@Resource
	private ActivityBaseService activityBaseService;

	@Resource
	private OrderHandleService orderHandleService;
	@Resource
	private PushBizzService pushBizzService;
	@Resource
	private HiCircleService hiCircleService;

	@Override
	protected BaseDao<ActivitySign> getBaseDao() {
		return activitySignDao;
	}

	@Override
	public Result handleSign(Integer buyerId, ActivitySign activitySign) throws OrderException {
		Result result = new Result();
		Timestamp now = TimeUtil.now();
		ActivityBaseVo baseVo = activityBaseService.getById(activitySign.getActivityId());
		if (now.getTime() > baseVo.getEndAt().getTime()) {
			throw new OrderException("亲，该活动已结束，无法报名。");
		}
		if (now.getTime() > baseVo.getSignEndAt().getTime()) {
			throw new OrderException("亲，该活动已截止报名，无法报名。");
		}
		if (baseVo.getStatus() == ActivityBaseStatusDictEnum.INVALID.getCode()) {
			throw new OrderException("亲，该活动已失效，无法报名。");
		}
		if (baseVo.getType() == ActivityBaseTypeDictEnum.COMMUNITY.getCode()) {// 社区活动
			boolean isJoin = communityJoinService.isJoinCommunity(baseVo.getBizzId(), buyerId);
			if (!isJoin) {
				throw new OrderException("亲，您非该社区用户。");
			}
		} else if (baseVo.getType() == ActivityBaseTypeDictEnum.CIRCLE.getCode()) {// 圈子活动
			boolean isCircleMember = circleMemberService.isCircleMember(buyerId, baseVo.getBizzId());
			if (!isCircleMember) {
				throw new OrderException("亲，您非该圈子成员。");
			}
		}
		ActivitySignQuery activitySignQuery = new ActivitySignQuery();
		activitySignQuery.setUserId(buyerId);
		activitySignQuery.setActivityId(activitySign.getActivityId());
		ActivitySignVo activitySignVo = activitySignDao.getOne(activitySignQuery, new PageOrder());
		if (null != activitySignVo) {
			throw new OrderException("亲，您已经报名当前活动。");
		}
		ActivitySign sign = new ActivitySign();
		sign.setUserId(buyerId);
		sign.setActivityId(activitySign.getActivityId());
		sign.setStatus(ActivitySignStatusDictEnum.PROCEED.getCode());
		sign.setRemark(activitySign.getRemark());
		int signId = activitySignDao.insert(sign);
		if(signId>0 && baseVo.getType() == ActivityBaseTypeDictEnum.CIRCLE.getCode()){
			hiCircleService.inActivity(buyerId, baseVo.getBizzId());//荣誉系统--用户参加活动
		}

		if (baseVo.getCostType() != ActivityBaseCostTypeDictEnum.ONLINE.getCode()) {// 非在线支付
			return result;
		}
		// 付费活动
		UserBaseVo buyer = userBaseService.getById(buyerId);
		UserIdentityQuery userIdentityQuery = new UserIdentityQuery();
		userIdentityQuery.setUserId(buyerId);
		userIdentityQuery.setType(UserIdentityTypeDictEnum.PHONE.getCode());
		UserIdentityVo userIdentityVo = userIdentityService.getOne(userIdentityQuery, new PageOrder());
		// 订单
		OrderBase orderBase = new OrderBase();
		orderBase.setTotal(baseVo.getCost());
		// orderBase.setOrderNo("");
		orderBase.setTitle(baseVo.getName());
		orderBase.setImg(baseVo.getLogo());
		orderBase.setOrderType(OrderBaseOrderTypeDictEnum.ACTIVITY.getCode());
		orderBase.setBuyerId(buyerId);
		orderBase.setSellerId(baseVo.getCreatorId());
		orderBase.setOrderStatus(OrderBaseOrderStatusDictEnum.UNCOMPLETED.getCode());
		orderBase.setOrderStatusAt(TimeUtil.now());
		orderBase.setPayType(OrderBasePayTypeDictEnum.ONLINE.getCode());
		orderBase.setPayStatus(OrderBasePayStatusDictEnum.UNPAYED.getCode());
		orderBase.setDeliveryStatus(OrderBaseDeliveryStatusDictEnum.UNSEND.getCode());
		orderBase.setDeliveryStatusAt(TimeUtil.now());
		orderBase.setReturnStatus(OrderBaseReturnStatusDictEnum.NONEED.getCode());
		orderBase.setReturnStatusAt(TimeUtil.now());
		orderBase.setIsCallBack(YesNoEnum.NO.getCode());
		orderBase.setAutoExpireAt(TimeUtil.addMins(TimeUtil.now(), 15)); // 未付款情况下自动失效时间
		orderBase.setSubsidyType(OrderBaseSubsidyTypeDictEnum.NONE.getCode());
		orderBase.setSubsidy(BigDecimal.ZERO);
		
		List<OrderItem> orderItemList = new ArrayList<OrderItem>();
		OrderItem orderItem = new OrderItem();
		orderItem.setProductId(baseVo.getId());
		orderItem.setName(baseVo.getName());
		orderItem.setPrice(baseVo.getCost());
		orderItem.setQuntity(1);
		orderItem.setImg(baseVo.getLogo());
		orderItemList.add(orderItem);

		OrderDelivery orderDelivery = new OrderDelivery();
		orderDelivery.setType(OrderDeliveryTypeDictEnum.SELLERSEND.getCode());
		orderDelivery.setDeliveryName("");
		orderDelivery.setDeliveryNo("");
		orderDelivery.setHasNeedDelivery(YesNoEnum.NO.getCode());
		orderDelivery.setConsignee(buyer.getNick());
		orderDelivery.setPhone(userIdentityVo.getIdentity());
		orderDelivery.setAddress(baseVo.getAddress());
		orderDelivery.setFreight(BigDecimal.ZERO);
		orderDelivery.setSendDeliveryType(OrderDeliverySendDeliveryTypeDictEnum.SELLER.getCode());
		result = orderHandleService.createOrder(orderBase, orderDelivery, orderItemList);
		String orderNo = (String) result.get("orderNo");
		// 更新报名的orderNo
		ActivitySign updatSign = new ActivitySign();
		updatSign.setId(signId);
		updatSign.setOrderNo(orderNo);
		activitySignDao.updateById(updatSign);
		pushBizzService.orderSelected(orderNo);
		return result;
	}

	@Override
	public int handleCancle(Integer userId, Integer activityId) {
		ActivitySignQuery activitySignQuery = new ActivitySignQuery();
		activitySignQuery.setUserId(userId);
		activitySignQuery.setActivityId(activityId);
		activitySignQuery.setStatus(ActivitySignStatusDictEnum.PROCEED.getCode());
		ActivitySignVo activitySignVo = activitySignDao.getOne(activitySignQuery, new PageOrder());
		if (null != activitySignVo) {
			return activitySignDao.deleteById(activitySignVo.getId());
		}
		return 0;
	}

	@Override
	public int getSignCount(Integer activityId) {
		ActivitySignQuery activitySignQuery = new ActivitySignQuery();
		activitySignQuery.setActivityId(activityId);
		return activitySignDao.queryCount(activitySignQuery);
	}

	@Override
	public boolean isSign(Integer userId, Integer activityId) {
		ActivitySignQuery activitySignQuery = new ActivitySignQuery();
		activitySignQuery.setUserId(userId);
		activitySignQuery.setActivityId(activityId);
		int count = activitySignDao.queryCount(activitySignQuery);
		if (count > 0) {
			return true;
		}
		return false;
	}

	@Override
	public ActivitySignVo getSignByOrderNo(String orderNo) {
		return activitySignDao.getSignByOrderNo(orderNo);
	}

	@Override
	public boolean isFirstSignActivity(Integer userId) {
		ActivitySignQuery activitySign = new ActivitySignQuery();
		activitySign.setUserId(userId);
		return activitySignDao.queryCount(activitySign) == 0;
	}
	
	@Override
	public List<ActivitySignVo> myLastSomeSigns(Integer userId, Integer some) {
		ActivitySignQuery signQ = new ActivitySignQuery();
		signQ.setUserId(userId);
		Pageable pageKit = new PageKit(1,some, new PageOrder(Direction.DESC, "newAt"));
		return activitySignDao.queryList(signQ, pageKit);
	}

	@Override
	public Integer getCountByUserId(Integer userId) {
		ActivitySignQuery activitySign = new ActivitySignQuery();
		activitySign.setUserId(userId);
		return activitySignDao.queryCount(activitySign);
	}
}